const express = require('express');
const router = express.Router();
const MySqlHelper = require('../common/MySqlHelper');
const client = require('../common/ServiceClient');
const MsgJsonHelper = require('../common/MsgJsonHelper');
const QueryModel = require('../common/QueryModel');
const MemoryCondition = require('../common/MemoryCondition');
const {
	DataAccess,
	MType,
	MLogic,
	MOperator,
	SortParam,
	Direction,
	OperationEnum,
	Public,
} = require('msg-dataaccess-base');
const Routebase = require('./route.base');
const ZK_LIULIANG = require('../model/ZK_LIULIANG');

const ds = new DataAccess();

router.all('*', (req, res, next) => {
	if (Routebase.IsLogin(req, res)) {
		if (Routebase.IsPermit(req, res, '00018')) {
			next();
		}
	}
});

/**
 * 访问图表(原始数据，未分组)
 */
router.get('/charts', (req, res) => {
	let start = req.query['START'] === undefined ? '' : req.query['START'].toString();
	let end = req.query['END'] === undefined ? '' : req.query['END'].toString();
	if (!start || !end) {
		return res.json(MsgJsonHelper.DebugJson('参数异常'));
	}
	let sqlsrt =
		"select * from ZK_LIULIANG where ZK_TIME Between '" +
		start +
		"' and '" +
		end +
		"' and EB_ISDELETE = '0' order by ZK_TIME asc";
	ds.GetTable(sqlsrt)
		.then(dt => {
			if (dt.length > 0) {
				res.json(MsgJsonHelper.DefaultJson(dt, true, dt.toString()));
			} else {
				res.json(MsgJsonHelper.DebugJson('暂无更多信息'));
			}
		})
		.catch(() => {
			res.json(MsgJsonHelper.DebugJson('流量图表接口请求异常'));
		});
});

/**
 * 获取流量分析
 */
router.get('/analysis', (req, res) => {
	let from = req.query['FROM'] || '';
	let to = req.query['TO'] || ''; // sql中自动往后加一天，因为sql筛选不包括结束日期，所以加一天
	if (!from || !to) {
		return res.json(MsgJsonHelper.DebugJson('请选择时间范围'));
	}
	const wherestr = ` EB_ISDELETE = '0' AND  ZK_TIME Between DATE_FORMAT('${from}','%Y-%m-%d') AND DATE_ADD(DATE_FORMAT('${to}','%Y-%m-%d'),INTERVAL 1 DAY) `;
	// 类型汇总
	const typesql = `
		SELECT
			count( * ) AS total,
			( SELECT count( * ) FROM ZK_LIULIANG WHERE lower( ZK_AGENT ) LIKE '%iphone%' AND ${wherestr}) AS iphone,
			( SELECT count( * ) FROM ZK_LIULIANG WHERE lower( ZK_AGENT ) LIKE '%android%' AND ${wherestr}) AS android
		FROM
			ZK_LIULIANG WHERE ${wherestr};
	`;
	// 天数汇总
	const daysql = `
		SELECT
			DATE_FORMAT( ZK_TIME, '%Y%m%d' ) AS days,
			count( * ) AS total
		FROM
			ZK_LIULIANG
		WHERE ${wherestr}
		GROUP BY
			days
		ORDER BY
			days ASC;
	`;
	// 小时汇总
	const hoursql = `
	 	SELECT
	 		DATE_FORMAT( ZK_TIME, '%h' ) AS hours,
	 		count( * ) AS total
	 	FROM
	 		ZK_LIULIANG
	 	WHERE ${wherestr}
	 	GROUP BY
	 		hours
	 	ORDER BY
	 		hours ASC;
	`;
	ds.GetTable(typesql + daysql + hoursql)
		.then(dt => {
			if (dt.length === 3) {
				let first = [],
					second = [],
					third = [];
				Object.keys(dt[0]).forEach(key => {
					dt[0][key].pc = dt[0][key].total - dt[0][key].iphone - dt[0][key].android;
					first.push(dt[0][key]);
				});
				Object.keys(dt[1]).forEach(key => {
					second.push(dt[1][key]);
				});
				Object.keys(dt[2]).forEach(key => {
					third.push(dt[2][key]);
				});
				res.json(
					MsgJsonHelper.DefaultJson(
						{
							first,
							second,
							third,
						},
						true,
						''
					)
				);
			} else {
				res.json(MsgJsonHelper.DebugJson('接口数据异常'));
			}
		})
		.catch(() => {
			res.json(MsgJsonHelper.DebugJson('analysis接口异常'));
		});
});

/**
 * 获取历史记录
 */
router.get('/history', (req, res) => {
	let from = req.query['FROM'] || '';
	let to = req.query['TO'] || '';
	let pagesize = req.query['PAGESIZE'] === undefined ? '1' : req.query['PAGESIZE'].toString();
	let pageno = req.query['PAGENO'] === undefined ? '1' : req.query['PAGENO'].toString();
	let condition = [];
	if (!from || !to) {
		return res.json(MsgJsonHelper.DebugJson('请选择时间范围'));
	}
	condition.push(
		new MemoryCondition({
			Field: 'ZK_TIME',
			Logic: MLogic.And,
			Operator: MOperator.Between,
			Type: MType.Mstring,
			value: [from, to],
		})
	);
	let sort = new SortParam({
		Field: 'ZK_TIME',
		SortDirection: Direction.DESC,
	});
	client
		.Query(
			QueryModel.ZK_LIULIANG,
			condition,
			null,
			Number.parseInt(pagesize, 10),
			Number.parseInt(pageno, 10),
			true,
			sort
		)
		.then(m => {
			if (m.result.length > 0) {
				res.json(MsgJsonHelper.DefaultJson(m.result, true, m.recordcount.toString()));
			} else {
				res.json(MsgJsonHelper.DebugJson('暂无更多信息'));
			}
		})
		.catch(err => {
			res.json(MsgJsonHelper.DebugJson('history接口请求异常'));
		});
});

module.exports = router;
